<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
    <!-- 移动端优化的登录界面 -->
    <div class="flex flex-col justify-center py-12 sm:px-6 lg:px-8">
      <div class="sm:mx-auto sm:w-full sm:max-w-md">
        <!-- Logo 和标题 -->
        <div class="text-center">
          <img class="mx-auto h-16 w-16" src="/vite.svg" alt="Logo">
          <h2 class="mt-6 text-3xl font-bold text-gray-900">
            {{ loginType === 'student' ? '学生登录' : '管理员登录' }}
          </h2>
          <p class="mt-2 text-sm text-gray-600">
            新生报到服务平台
          </p>
          
          <!-- 端口切换 -->
          <div class="mt-4 flex justify-center">
            <div class="bg-gray-100 p-1 rounded-lg">
              <button
                @click="switchLoginType('student')"
                :class="[
                  'px-4 py-2 text-sm font-medium rounded-md transition-colors duration-200',
                  loginType === 'student' 
                    ? 'bg-blue-500 text-white shadow-sm' 
                    : 'text-gray-600 hover:text-gray-900'
                ]"
              >
                学生端
              </button>
              <button
                @click="switchLoginType('admin')"
                :class="[
                  'px-4 py-2 text-sm font-medium rounded-md transition-colors duration-200',
                  loginType === 'admin' 
                    ? 'bg-blue-500 text-white shadow-sm' 
                    : 'text-gray-600 hover:text-gray-900'
                ]"
              >
                管理端
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div class="card mx-4 sm:mx-0">
          <form class="space-y-6" @submit.prevent="handleLogin">
            <!-- 手机号输入 -->
            <div>
              <label for="phone" class="block text-sm font-medium text-gray-700">
                手机号
              </label>
              <div class="mt-1">
                <input
                  id="phone"
                  v-model="form.phone"
                  name="phone"
                  type="tel"
                  required
                  class="input"
                  placeholder="请输入手机号"
                  :disabled="loading"
                  maxlength="11"
                >
              </div>
              <p v-if="errors.phone" class="mt-1 text-sm text-red-600">
                {{ errors.phone }}
              </p>
            </div>

            <!-- 考生号输入 -->
            <div>
              <label for="candidateNum" class="block text-sm font-medium text-gray-700">
                考生号
              </label>
              <div class="mt-1">
                <input
                  id="candidateNum"
                  v-model="form.candidateNum"
                  name="candidateNum"
                  type="text"
                  required
                  class="input"
                  placeholder="请输入考生号"
                  :disabled="loading"
                  maxlength="20"
                >
              </div>
              <p v-if="errors.candidateNum" class="mt-1 text-sm text-red-600">
                {{ errors.candidateNum }}
              </p>
            </div>

            <!-- 验证码 (可选功能) -->
            <div v-if="showCaptcha">
              <label for="captcha" class="block text-sm font-medium text-gray-700">
                验证码
              </label>
              <div class="mt-1 flex space-x-3">
                <input
                  id="captcha"
                  v-model="form.captcha"
                  name="captcha"
                  type="text"
                  class="input flex-1"
                  placeholder="请输入验证码"
                  :disabled="loading"
                  maxlength="6"
                >
                <button
                  type="button"
                  @click="sendCaptcha"
                  :disabled="loading || captchaCountdown > 0"
                  class="px-4 py-2 text-sm font-medium text-blue-500 border border-blue-500 rounded-md hover:bg-blue-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {{ captchaCountdown > 0 ? `${captchaCountdown}s` : '获取验证码' }}
                </button>
              </div>
              <p v-if="errors.captcha" class="mt-1 text-sm text-red-600">
                {{ errors.captcha }}
              </p>
            </div>

            <!-- 记住登录状态 -->
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <input
                  id="remember-me"
                  v-model="form.remember"
                  name="remember-me"
                  type="checkbox"
                  class="h-4 w-4 text-blue-500 focus:ring-blue-500 border-gray-300 rounded"
                >
                <label for="remember-me" class="ml-2 block text-sm text-gray-900">
                  记住登录状态
                </label>
              </div>

              <div class="text-sm">
                <a href="#" class="font-medium text-blue-500 hover:text-blue-600">
                  登录帮助
                </a>
              </div>
            </div>

            <!-- 错误提示 -->
            <div v-if="errorMessage" class="rounded-md bg-red-50 p-4">
              <div class="flex">
                <div class="flex-shrink-0">
                  <XCircleIcon class="h-5 w-5 text-red-400" />
                </div>
                <div class="ml-3">
                  <h3 class="text-sm font-medium text-red-800">
                    登录失败
                  </h3>
                  <div class="mt-2 text-sm text-red-700">
                    {{ errorMessage }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 登录按钮 -->
            <div>
              <button
                type="submit"
                :disabled="loading"
                class="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-500 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
              >
                <span class="absolute left-0 inset-y-0 flex items-center pl-3">
                  <DevicePhoneMobileIcon class="h-5 w-5 text-blue-200 group-hover:text-blue-200" />
                </span>
                <span v-if="loading" class="flex items-center">
                  <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  登录中...
                </span>
                <span v-else>登录</span>
              </button>
            </div>
          </form>

          <!-- 测试账号提示 -->
          <div class="mt-6 p-4 bg-blue-50 rounded-lg">
            <h4 class="text-sm font-medium text-blue-800 mb-2">测试账号</h4>
            <div class="text-xs text-blue-700 space-y-1">
              <p>手机号: 13800138000</p>
              <p>考生号: 2024001001</p>
            </div>
          </div>

          <!-- 功能说明 -->
          <div class="mt-6 text-center">
            <div class="text-sm text-gray-600">
              <p class="mb-2">登录后可以：</p>
              <div class="grid grid-cols-2 gap-2 text-xs">
                <div class="flex items-center">
                  <CheckCircleIcon class="h-4 w-4 text-green-500 mr-1" />
                  <span>查看报到进度</span>
                </div>
                <div class="flex items-center">
                  <CheckCircleIcon class="h-4 w-4 text-green-500 mr-1" />
                  <span>在线缴费</span>
                </div>
                <div class="flex items-center">
                  <CheckCircleIcon class="h-4 w-4 text-green-500 mr-1" />
                  <span>提交信息</span>
                </div>
                <div class="flex items-center">
                  <CheckCircleIcon class="h-4 w-4 text-green-500 mr-1" />
                  <span>查看通知</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部链接 -->
        <div class="mt-6 text-center">
          <p class="text-sm text-gray-600">
            管理员登录请访问
            <router-link to="/admin/login" class="font-medium text-blue-500 hover:text-blue-600">
              管理端
            </router-link>
          </p>
          
          <div class="mt-4">
            <router-link to="/student/contact" class="text-sm text-gray-500 hover:text-gray-700">
              联系我们 | 使用帮助
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../../stores'
import { validatePhone } from '../../utils'
import {
  DevicePhoneMobileIcon,
  XCircleIcon,
  CheckCircleIcon
} from '@heroicons/vue/24/outline'

const router = useRouter()
const authStore = useAuthStore()

// 登录类型
const loginType = ref('student')

// 表单数据
const form = reactive({
  phone: '',
  candidateNum: '',
  captcha: '',
  remember: false
})

// 表单验证错误
const errors = reactive({
  phone: '',
  candidateNum: '',
  captcha: ''
})

// 状态
const loading = ref(false)
const errorMessage = ref('')
const showCaptcha = ref(false) // 是否显示验证码
const captchaCountdown = ref(0) // 验证码倒计时

// 切换登录类型
const switchLoginType = (type) => {
  loginType.value = type
  if (type === 'admin') {
    router.push('/admin/login')
  }
}

// 表单验证
const validateForm = () => {
  errors.phone = ''
  errors.candidateNum = ''
  errors.captcha = ''
  
  // 验证手机号
  if (!form.phone.trim()) {
    errors.phone = '请输入手机号'
    return false
  }
  
  if (!validatePhone(form.phone)) {
    errors.phone = '请输入正确的手机号'
    return false
  }
  
  // 验证考生号
  if (!form.candidateNum.trim()) {
    errors.candidateNum = '请输入考生号'
    return false
  }
  
  if (form.candidateNum.length < 10) {
    errors.candidateNum = '考生号长度不能少于10位'
    return false
  }
  
  // 如果显示验证码，验证验证码
  if (showCaptcha.value) {
    if (!form.captcha.trim()) {
      errors.captcha = '请输入验证码'
      return false
    }
    
    if (form.captcha.length !== 6) {
      errors.captcha = '验证码长度应为6位'
      return false
    }
  }
  
  return true
}

// 发送验证码
const sendCaptcha = async () => {
  // 先验证手机号
  if (!form.phone.trim()) {
    errors.phone = '请先输入手机号'
    return
  }
  
  if (!validatePhone(form.phone)) {
    errors.phone = '请输入正确的手机号'
    return
  }
  
  try {
    // 模拟发送验证码API调用
    // await authAPI.sendCaptcha(form.phone)
    
    // 开始倒计时
    captchaCountdown.value = 60
    const timer = setInterval(() => {
      captchaCountdown.value--
      if (captchaCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    
    // 显示成功提示
    console.log('验证码已发送到手机号:', form.phone)
  } catch (error) {
    console.error('Send captcha failed:', error)
    errors.captcha = '验证码发送失败，请稍后重试'
  }
}

// 处理登录
const handleLogin = async () => {
  if (!validateForm()) {
    return
  }
  
  loading.value = true
  errorMessage.value = ''
  
  try {
    const result = await authStore.login({
      phone: form.phone,
      candidateNum: form.candidateNum,
      captcha: form.captcha,
      remember: form.remember
    }, 'student')
    
    if (result.success) {
      // 登录成功，跳转到学生首页
      router.push('/student/home')
    } else {
      errorMessage.value = result.message || '登录失败，请检查手机号和考生号'
    }
  } catch (error) {
    console.error('Login error:', error)
    errorMessage.value = '登录失败，请稍后重试'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
@reference "../../style.css";

/* 移动端优化样式 */
@media (max-width: 640px) {
  .card {
    @apply mx-4;
  }
}
</style>